package com.xlh.service.impl;

import cn.hutool.core.util.URLUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xlh.common.Result;
import com.xlh.common.ResultEnum;
import com.xlh.dao.SystemProblemReportMapper;
import com.xlh.dao.SystemProblemReportMapperExt;
import com.xlh.dto.PageDTO;
import com.xlh.dto.SystemProblemReportDTO;
import com.xlh.dto.SystemProblemReportExcelDTO;
import com.xlh.enums.SystemProblemReportExcelCellEnum;
import com.xlh.enums.user.RoleEnum;
import com.xlh.param.ReportSystemProblemParam;
import com.xlh.pojo.SystemProblemReport;
import com.xlh.service.SystemProblemReportService;
import com.xlh.util.BeanUtil;
import com.xlh.util.ExcelsUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zhr 2019/1/28
 */
@Service
public class SystemProblemReportServiceImpl implements SystemProblemReportService {

    // 下载excel的基本常量信息
    private static final String FILE_NAME = "问题反馈.xls";

    // 业务日志
    private static final Logger logger = LoggerFactory.getLogger(SystemProblemReportServiceImpl.class);

    @Autowired
    private SystemProblemReportMapper systemProblemReportMapper;

    @Autowired
    private SystemProblemReportMapperExt systemProblemReportMapperExt;

    @Override
    public void reportSystemProblem(ReportSystemProblemParam param, Long userId) {
        // 创建问题反馈对象并放入参数
        SystemProblemReport systemProblemReport = BeanUtil.transform(SystemProblemReport.class, param);
        systemProblemReport.setUserId(userId);

        // 插入问题反馈内容
        systemProblemReportMapper.insertSelective(systemProblemReport);
    }

    @Override
    public PageDTO<SystemProblemReportDTO> listSystemProblem(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<SystemProblemReportDTO> list = listSystemProblemReports();
        // 创建分页
        PageInfo<SystemProblemReportDTO> pageInfo = new PageInfo<>(list);
        return new PageDTO<>(pageInfo);
    }

    @Override
    public Result downloadSystemProblem() {
        List<SystemProblemReportDTO> list = listSystemProblemReports();

        List<SystemProblemReportExcelDTO> excelList = batchConvert(list);

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        // 导出excel
        try (Workbook wb = ExcelsUtil.createWorkBook(excelList, SystemProblemReportExcelCellEnum.class)) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + FILE_NAME + ";filename*=UTF-8''" + URLUtil.encode(FILE_NAME));

            wb.write(response.getOutputStream());
        } catch (IOException | IllegalAccessException e) {
            logger.error(e.getMessage(), e);
            return Result.error(ResultEnum.EXCEL_OUTPUT_EXCEPTION);
        }

        return Result.success();
    }

    private List<SystemProblemReportExcelDTO> batchConvert(List<SystemProblemReportDTO> list) {
        List<SystemProblemReportExcelDTO> resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SystemProblemReportDTO dto : list) {
                resultList.add(new SystemProblemReportExcelDTO(dto));
            }
        }
        return resultList;
    }

    private List<SystemProblemReportDTO> listSystemProblemReports() {
        List<SystemProblemReportDTO> list = systemProblemReportMapperExt.listSystemProblemReports();
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(dto -> {
                RoleEnum roleEnum = RoleEnum.getByCode(dto.getRole());
                if (roleEnum != null) dto.setRoleName(roleEnum.getRoleName());
            });
        }
        return list;
    }
}
